<?php


namespace app\admin\system\controller;


use app\admin\system\logic\DeptLogic;
use app\admin\system\validate\DeptValidate;
use app\common\controller\BaseAdminController;
use core\utils\TreeUtil;

/**
 * 部门管理
 * Class UserLabelController
 * @package app\admin\user\controller
 */
class DeptController extends BaseAdminController
{
    protected function init()
    {
        parent::init();
        $this->logic = new DeptLogic();
        $this->validate = new DeptValidate();
    }

    protected function searchWhere()
    {
        $where = [
            ['status', '<>', -1]
        ];
        $this->form['name'] && $where[] = ['name', 'like', "%" . $this->form['name'] . "%"];
        return $where;
    }

    public function list()
    {
        $query = $this->logic->search($this->searchWhere());
        $query->order($this->listOrder());
        $data = $this->logic->getList($query, '*,name as label');
        $data = TreeUtil::getTree($data);
        return $this->success($data);
    }

    public function beforeAddOrEdit($type, &$data)
    {
        if ($data['pid']) {
            $pidInfo = $this->logic->where(['id' => $data['pid']])->field(['id', 'path'])->find();
            if ($pidInfo) {
                if ($pidInfo['path']) {
                    $data['path'] = implode(',', [$pidInfo['path'], $pidInfo['id']]);
                } else {
                    $data['path'] = $pidInfo['id'];
                }
            }
        }
        parent::beforeAddOrEdit($type, $data);
    }

    public function remove()
    {
        $ids = request()->input('ids', [request()->input($this->idKey)]);
        if (!empty($ids)) {
            $one = $this->logic->where([
                ['pid', 'in', $ids],
                ['status', '<>', -1],
            ])->find();
            if ($one) {
                return $this->error('含有下级部门不可删除');
            }
            $this->logic->where([
                ['id', 'in', $ids]
            ])->update([
                'status' => -1
            ]);
            return $this->success();
        } else {
            return $this->error('参数错误，请检查');
        }
    }
}